package cn.oms.esb.provider.common.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Map;

public class BeanUtil {

    public static <T> T map2bean(Map<String, Object> map, Class<T> classType) {
        //采用反射动态创建对象
        T obj = null;
        try {
            obj = classType.newInstance();
            //获取对象字节码信息,不要Object的属性
            BeanInfo beanInfo = Introspector.getBeanInfo(classType, Object.class);
            //获取bean对象中的所有属性
            PropertyDescriptor[] list = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : list) {
                String key = pd.getName();    //获取属性名
                Object value = map.get(key);  //获取属性值
                value = value.toString();
                pd.getWriteMethod().invoke(obj, value);//调用属性setter()方法,设置到javabean对象当中
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

}
